package com.zjc.springboot.delayqueue.redis;

import com.zjc.springboot.delayqueue.event.Msg;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

public class RedisClient {

    public static final String PREFIX_KEY = "zjc:delay:queue:";
    public static final String PREFIX_VALUE_KEY = "zjc:delay:queue:value:";

    StringRedisTemplate stringRedisTemplate;

    public RedisClient(StringRedisTemplate stringRedisTemplate) {

        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void sendMsg(Msg msg) {
        stringRedisTemplate.opsForValue().set(PREFIX_KEY + msg.getKey(), "", msg.getTime(), TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set(PREFIX_VALUE_KEY + msg.getKey(), msg.getValue());
    }

    public Msg getMsg(String key) {
        String value = stringRedisTemplate.opsForValue().get(PREFIX_VALUE_KEY + key);
        Msg msg = new Msg();
        msg.setKey(key);
        msg.setValue(value);
        return msg;
    }

    public void deleteMsg(String key) {
        stringRedisTemplate.delete(PREFIX_VALUE_KEY + key);
    }
}
